package com.llb666.e.shop.domain.service;

import com.llb666.e.shop.api.dto.MerchantOrdersDto;
import com.llb666.e.shop.domain.entity.PayOrders;
import com.llb666.e.shop.domain.repository.PaymentOrderRepository;
import lombok.RequiredArgsConstructor;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author llb666
 * @date 2022/9/16 22:23
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class PaymentOrderService {

    private final PaymentOrderRepository paymentOrderRepository;

    private final Sid sid;

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public String updateOrderPaid(String merchantOrderId, Integer paidAmount) {
        paymentOrderRepository.updateOrderPaid(merchantOrderId,paidAmount);
        PayOrders payOrders = paymentOrderRepository.queryMerchantPayOrder(merchantOrderId);
        return payOrders.getReturnUrl();
    }

    public PayOrders queryOrderInfo(String merchantUserId, String merchantOrderId) {
        return paymentOrderRepository.queryOrderInfo(merchantUserId,merchantOrderId);
    }

    public PayOrders queryOrderByStatus(String merchantUserId, String merchantOrderId, Integer type) {
        return paymentOrderRepository.queryOrderByStatus(merchantUserId,merchantOrderId,type);
    }

    public boolean createPaymentOrder(MerchantOrdersDto merchantOrdersDto) {
        String paymentOrderId = sid.nextShort();
        PayOrders paymentOrder = merchantOrdersDto.covert(paymentOrderId);
        int result = paymentOrderRepository.insert(paymentOrder);
        return result == 1;
    }
}
